<?php
namespace Dft\Controllers;

use Imagick;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Silex\ControllerCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class AssetCSP implements ControllerProviderInterface {

	public function connect(Application $app) {
		$controllers = $app['controllers_factory'];
		$controllers->match('/image/{id}/', array($this,'image'), 'GET')->bind('view-image-original');
		$controllers->match('/image/{id}/{size}/', array($this,'image'), 'GET')->bind('view-image');
		return $controllers;
	}

	public function image(Application $app, Request $request, $id, $size = null) {
		$repo = $app['em']->getRepository('Secret\Entities\Content');
		$content = $repo->data('Asset', 'entity.id = ' . $id);
		if (count($content['_data']) == 0) {
			$app->abort(404);
		}
		$fileType = $content['_data'][0]['fileType'];
		$fileName = $content['_data'][0]['name'];
		$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/../uploads/' . $content['_data'][0]['nameOnServer'];
		if (file_exists($file) && getimagesize($file) && $size) {
			$size = $repo->data('Thumbnail size', 'entity.width = :v1', array('v1' => $size));
			if (count($size['_data']) == 0) {
				$app->abort(404);
			}
			$cache = dirname($_SERVER['SCRIPT_FILENAME']) . '/../cache/image/';
			if (! file_exists($cache)) {
				mkdir($cache, 0777, true);
			}
			$thumbnail = $cache . md5($content['_data'][0]['id'] . '-' . $size['_data'][0]['width']) . '.' . $content['_data'][0]['fileExt'];
			if (!file_exists($thumbnail)) {
				$image = new Imagick($file);
				$image->adaptiveResizeImage($size['_data'][0]['width'], 0);
				$image->writeImage($thumbnail);
			}
			$file = $thumbnail;
		}
		if (! file_exists($file) || ! getimagesize($file)) {
			$file = dirname($_SERVER['SCRIPT_FILENAME']) . '/../../_cdn/htdocs/default/images/noimage.jpg';
		}
		$stream = function () use($file) {
			readfile($file);
		};
		return $app->stream($stream, 200, array('Content-Type' => 'image/jpg','Content-length' => filesize($file),'Content-Disposition' => 'filename="' . $fileName . '"'));
	}
}